<template>
  <el-dialog :title="formData.roleUuid ? '修改' : '添加'" width="30%" :model-value="dialog" @close="close">
    <el-form :model="formData" :rules="rules" ref="uploadForm" label-width="auto" style="padding: 0 20px" class="Dform">
      <el-form-item label="角色名称：" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit()">提交</el-button>
        <el-button v-if="!formData.roleUuid" @click="resetForm()">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, ref, PropType, watch, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { updateRole, saveRole } from '@/api/system'

export default defineComponent({
  components: {
  },
  props: {
    dialog: {
      type: Boolean,
      default: false,
    },
    currentForm: {
      type: Object,
      default: () => { },
    },
    selectMenuList: {
      type: Array as PropType<{ title: string; id: string | number }[]>,
      default: () => [],
    },
  },
  emits: ['update:currentForm', 'update:dialog', 'refresh'],
  setup(props, context) {
    const formData = reactive(props.currentForm)
    const uploadForm = ref<any>(null)
    watch(
      () => props.dialog,
      (val) => {
        if (val) {
          Object.assign(formData, props.currentForm)
          console.log(formData);
        }
      }
    )

    const close = () => {
      context.emit('update:dialog', false)
      context.emit('refresh', { ...formData })
      context.emit('update:currentForm', {})
    }

    const onSubmit = () => {
      uploadForm.value.validate((valid: boolean) => {
        if (valid) {
          if (formData.roleUuid) {
            updateRole(formData).then((res: any) => {
              if (res.code == 200) {
                ElMessage.success('修改成功')
                close()
              }
            })
          } else {
            saveRole(formData).then((res: any) => {
              if (res.code == 200) {
                ElMessage.success('添加成功')
                close()
              }
            })
          }
        } else {
          ElMessage({
            message: '验证失败',
            type: 'error',
            duration: 1000,
          })
          return false
        }
      })
    }

    const resetForm = () => {
      uploadForm.value.resetFields()
      context.emit('update:currentForm', {})
    }

    return {
      uploadForm,
      formData,
      close,
      resetForm,
      onSubmit,
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
        ],
      },
    }
  },
})
</script>

<style></style>
